import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'

const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8061/api/v1',
  timeout: 10000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'Accept': 'application/json; charset=UTF-8'
  }
})

request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 检查是否是标准的ApiResponse格式
    if (response.data && typeof response.data === 'object' && 'success' in response.data) {
      if (response.data.success) {
        return response.data.data
      } else {
        const error = new Error(response.data.message || '请求失败')
        // 添加响应状态和数据到错误对象中
        ;(error as any).response = { status: response.status, data: response.data }
        throw error
      }
    }
    return response.data
  },
  (error) => {
    console.error('请求错误:', error)
    // 如果是401错误，添加更多信息
    if (error.response?.status === 401) {
      console.log('401 错误详情:', error.response.data)
    }
    return Promise.reject(error)
  }
)

export { request }
export default request
